let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_COMPANY_VARIANT";
const ohana_instance = new ohana(tableName);
const ohana_instance_content = new ohana("SAP_JIANGDU_COMPANY_VARIANT_CONTENT");

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

async function getLastestCommunication(publisher, recipient) {
    let result = await ohana_instance.raw(
        'SELECT CO.*, RE.* FROM "SAP_JIANGDU_COOPERATE_REQUIREMENT" as CO LEFT JOIN "SAP_JIANGDU_MULTI_RECIPIENTS" as RE ON CO.COOPERATE_REQUIREMENT_ID = RE.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID WHERE RE.RECIPIENT_ID  =' +
        "'" +
        recipient +
        "'" +
        "AND CO.PUBLISHER = " +
        "'" +
        publisher +
        "'" +
        "ORDER BY CO.UPDATED_AT DESC"
    );
    if (result.length > 0) {
        return result[0].UPDATED_AT;
    } else {
        return "没有沟通记录";
    }
}

router.get("/", function (req, res, next) {
    // #swagger.tags = ['公司合集']
    // #swagger.summary = '获取列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    let user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    payload.USER_ID = user.user_id;

    getData(payload)
        .then((result) => {
            if (result.length == 0) {
                res.send(result);
            }
            let count = 0;
            result.forEach((element) => {
                getContents(user.user_id, element.COMPANY_VARIANT_ID).then(
                    (contents) => {
                        element.contents = contents;
                        count++;
                        if (count == result.length) {
                            res.send(result);
                        }
                    }
                );
            });
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.post("/", function (req, res, next) {
    // #swagger.tags = ['公司合集']
    // #swagger.summary = '插入列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/companyVarient_add"
                          }  
                      },
                  }
          } */
    let { data, contents } = req.body;
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    data.USER_ID = user.user_id;

    insertData(data, contents)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.put("/", function (req, res, next) {
    // #swagger.tags = ['公司合集']
    // #swagger.summary = '更新列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/companyVarient_update"
                          }  
                      },
                  }
          } */
    let { data, contents } = req.body;
    updateData(data, contents)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['公司合集']
    // #swagger.summary = '删除列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/companyVarient_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    deleteData(data)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getData(condition) {
    let result = [];
    if (!condition) {
        result = "请登录";
    } else {
        result = await ohana_instance.find(condition);
    }
    return result;
}

async function getContents(publisher, condition) {
    let result = await ohana_instance_content.raw(
        'SELECT A1.*, A2.USER_NAME, A2.LEVEL, A2.COMPANY_NAME, A2.INDUSTRY, A2.COMPANY_TYPE FROM "SAP_JIANGDU_COMPANY_VARIANT_CONTENT" as A1 LEFT JOIN ' +
        constants.REGISTEDUSERSTABLE +
        " as A2 ON A1.USER_ID = A2.USER_ID WHERE A1.COMPANY_VARIANT_ID_COMPANY_VARIANT_ID  ='" +
        condition +
        "'"
    );
    for (let index = 0; index < result.length; index++) {
        const content = result[index];
        let lastDate = "";
        let result1 = await ohana_instance.raw(
            'SELECT CO.*, RE.* FROM "SAP_JIANGDU_COOPERATE_REQUIREMENT" as CO LEFT JOIN "SAP_JIANGDU_MULTI_RECIPIENTS" as RE ON CO.COOPERATE_REQUIREMENT_ID = RE.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID WHERE RE.RECIPIENT_ID  =' +
            "'" +
            content.USER_ID +
            "'" +
            "AND CO.PUBLISHER = " +
            "'" +
            publisher +
            "'" +
            "ORDER BY CO.UPDATED_AT DESC"
        );
        if (result1.length > 0) {
            lastDate = result1[0].UPDATED_AT;
        } else {
            lastDate = "没有沟通记录";
        }
        content.LAST_COMMU_DATE = lastDate;
    }
    return result;
}

async function insertData(data, contents) {
    let newId = uunewid.v4();
    data.COMPANY_VARIANT_ID = newId;
    let result = await ohana_instance.insert(data);
    contents.forEach((content) => {
        let item = {};
        item.COMPANY_VARIANT_CONTENT_ID = uunewid.v4();
        item.COMPANY_VARIANT_ID_COMPANY_VARIANT_ID = newId;
        item.USER_ID = content;
        ohana_instance_content.insert(item);
    });
    return result;
}

async function updateData(data, contents) {
    let result = await ohana_instance.update(
        {
            COMPANY_VARIANT_ID: data.COMPANY_VARIANT_ID,
        },
        data
    );

    await ohana_instance_content.raw(
        'delete from "SAP_JIANGDU_COMPANY_VARIANT_CONTENT" where COMPANY_VARIANT_ID_COMPANY_VARIANT_ID = \'' +
        data.COMPANY_VARIANT_ID +
        "'"
    );

    await contents.forEach((content) => {
        let item = {};
        item.COMPANY_VARIANT_CONTENT_ID = uunewid.v4();
        item.COMPANY_VARIANT_ID_COMPANY_VARIANT_ID = data.COMPANY_VARIANT_ID;
        item.USER_ID = content;
        ohana_instance_content.insert(item);
    });
    return result;
}

async function deleteData(data) {
    let result1 = await ohana_instance.raw(
        'delete from "' +
        tableName +
        "\" where COMPANY_VARIANT_ID = '" +
        data.COMPANY_VARIANT_ID +
        "'"
    );

    let result2 = await ohana_instance_content.raw(
        'delete from "SAP_JIANGDU_COMPANY_VARIANT_CONTENT" where COMPANY_VARIANT_ID_COMPANY_VARIANT_ID = \'' +
        data.COMPANY_VARIANT_ID +
        "'"
    );

    return { result1, result2 };
}

module.exports = router;
